package com.atguigu.typehandler;

import com.atguigu.entity.Address;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author : leimingchao
 * @version V1.0
 * @Project: common_mapper
 * @Package com.atguigu.typehandler
 * @Description: TODO
 * @date Date : 2021年05月24日 22:15
 */
public class AddressTypeHandler extends BaseTypeHandler<Address> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Address address, JdbcType jdbcType) throws SQLException {
        if (address==null){
            return;
        }

        String province = address.getProvince();
        String city = address.getCity();
        String street = address.getStreet();

        StringBuilder sb = new StringBuilder();
        sb.append(province).append(",").append(city).append(",").append(street);
        ps.setString(i,sb.toString());
    }

    @Override
    public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")){
            return null;
        }

        String[] array = columnValue.split(",");
        String province = array[0];
        String city =  array[1];
        String street = array[2];

        Address address = new Address(province,city,street);

        return address;
    }

    @Override
    public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")){
            return null;
        }

        String[] array = columnValue.split(",");
        String province = array[0];
        String city =  array[1];
        String street = array[2];

        Address address = new Address(province,city,street);

        return address;
    }

    @Override
    public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")){
            return null;
        }

        String[] array = columnValue.split(",");
        String province = array[0];
        String city =  array[1];
        String street = array[2];

        Address address = new Address(province,city,street);

        return address;
    }
}
